<?php

class PrizeAction extends BaseAction {

    public $option_bal = array(1=>'已联通结算',2=>'已物流结算');
    public function hassend(){
        $this->assign('opt',2);
        $this->assign('option_bal',$this->option_bal);
        $this->index(1);
    }

    public function unsend(){
        $this->assign('opt',1);
        $this->index(0);
    }

    public function index($status=-1){

        switch($this->userinfo['roleid']){
            case 1:
                $isAdmin = true;$isWL = false;
                break;
            case 3:
                $isAdmin = false;$isWL = true;
                break;
            default:
                $isAdmin = false;$isWL = false;
        }
        $map = array();
        import('ORG.Util.Page');// 导入分页类
        $stat = $this->_param('status');
        $sort = $this->_param('sort');
        $cate = $this->_param('cate');
        $psize = $this->_param('psize',20);
        $exp = $this->_param('exp');
        $receive_name = $this->_param('receive_name','trim');
        $status = isset($stat) ? $stat : $status;

        if(isset($status) && $status>-1){
            $map[] = "a.status='$status'";
        }
        if($isWL && $this->userinfo['attr']){
            $map[] = "a.kd_id=".$this->userinfo['attr'];//取出所属快递公司
        }
        if(isset($exp) && $exp){
            $map[] = "a.kd_id=".$exp;//取出所属快递公司
        }
        if(isset($sort) && !empty($sort)){
            $map[] = "b.sort='$sort'";
        }
        if(isset($cate) && !empty($cate)){
            $map[] = "b.categray='$cate'";
        }
        if (isset($receive_name) && !empty($receive_name)) {
            $map[] = "a.username='$receive_name'";
        }
        $pagesize = $psize ? $psize : 20;
        $model = new Model();
        $where = implode(' and ',$map);
        $sql = "select count(*) as num from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where ";
        $count      = $model->query($sql);// 查询满足要求的总记录数 $map表示查询条件
        $Page       = new Page($count[0]['num'],$pagesize);// 实例化分页类 传入总记录数
        $show       = $Page->show();// 分页显示输出
        $offset = $Page->firstRow;

        $order = "id desc"; //排序
        $sql = "select a.*,b.sort,b.categray from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where order by $order limit $offset,$pagesize ";
        $list = $model->query($sql);

        $this->assign('list',$list);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('query',array('status'=>$status,'sort'=>$sort,'cate'=>$cate,'exp'=>($isWL && $this->userinfo['attr'])?$this->userinfo['attr']:$exp,'psize'=>$psize,'receive_name'=>$receive_name));
        //查询所有物流商户
        $this->assign('express',getExpress(true));
        //输出是否是管理员
        $this->assign('isAdmin',$isAdmin);
        //分类，商品级别
        $this->assign('sortarr',D('Goods')->getSortarr());
        $this->assign('categray',D('Goods')->getCategray());
        $this->display("index");
    }

    /**
     * 发放奖品
     * @return [type] [description]
     */
    public function send()
    {
        $id = $this->_param('id');
        $kdcode = $this->_param('kdcode');
        if($id && $kdcode)
        {
            $row = M('Prize')->where(array('id'=>$id))->field('sncode,status')->find();
            if($row['status']==0)
            {
                $re = M('Prize')->where(array('id'=>$id))->save(array('status'=>1,'kdcode'=>$kdcode));
                if($re!==false)
                {
                    //把商品设置为已配送
                    M('Goods')->where(array('sncode'=>$row['sncode']))->save(array('issend'=>1,'send_time'=>time()));
                    $ret = returnJson('200','','操作成功');
                }else
                {
                    $ret = returnJson('400','','操作失败');
                }
            }else{
                $ret = returnJson('401','','该商品已配送了');
            }
            echo $ret;exit;
        }
    }

    public function selectKd()
    {
        $ids_str = $this->_param('ids');
        $kdtype = $this->_param('kdtype',0);

        $ids_str = urldecode($ids_str);
        $ids = json_decode($ids_str,true);
        if($ids && $kdtype){
            $w_ids = "id in (".implode(',',$ids).")";
            $re = M('Prize')->where($w_ids)->save(array('kd_id'=>$kdtype));
            if($re){
                $ret = returnJson('200','','操作成功');
            }else{
                $ret = returnJson('400','','操作失败');
            }
        }else{
            $ret = returnJson('401','','请选择操作数据');
        }
        echo $ret;exit;
    }

    /**
     * 选择已经结算的公司
     */
    public function selectBal()
    {
        $data = array();
        $ids_str = $this->_param('ids');
        $optbal = $this->_param('opt_bal',0);

        $ids_str = urldecode($ids_str);
        $ids = json_decode($ids_str,true);
        if($ids && $optbal){
            $w_ids = "id in (".implode(',',$ids).")";
            switch($optbal){
                case 1:
                    $data['lt_bal'] = 1;break;
                case 2:
                    $data['wl_bal'] = 1;break;
            }
            $re = M('Prize')->where($w_ids)->save($data);
            if($re){
                $ret = returnJson('200','','操作成功');
            }else{
                $ret = returnJson('400','','操作失败');
            }
        }else{
            $ret = returnJson('401','','请选择操作数据');
        }
        echo $ret;exit;
    }
    //联通已结算
    public function LTbalance(){
        $this->balance('1',1);
    }

    //物流已结算
    public function WLbalance(){

        switch($this->userinfo['roleid']){
            case 1:
                $isAdmin = true;$isWL = false;
                break;
            case 3:
                $isAdmin = false;$isWL = true;
                break;
            default:
                $isAdmin = false;$isWL = false;
        }
        if($isWL && $this->userinfo['attr']){
            $kdtype = $this->userinfo['attr'];//取出所属快递公司
        }
        if($isAdmin && I('exp')){
            $kdtype = I('exp');
        }
        $this->balance('2',1,$kdtype);
    }

    public function balance($type,$status,$kdtype=0){
        import('ORG.Util.Page');// 导入分页类
        $model = new Model();
        $startime = $this->_post('starttime',0);
        $endtime = $this->_post('endtime',0);

        $where = "a.status='$status' ";
        if($kdtype){
            $where .= "and a.kd_id='$kdtype' ";
        }
        if($type=='1'){
            $where .= "and a.lt_bal=1 ";//联通已结算
        }elseif($type=='2'){
            $where .= "and a.wl_bal=1 ";//物流已结算
        }
        if($startime && $endtime){
            if (strtotime($startime)<strtotime($endtime)) {
                $where .= "and (a.create_time>".strtotime($startime)." and a.create_time<".strtotime($endtime).") ";
            }else{
                $this->_error('开始时间须小于结束时间');exit();
            }
            
        }
//        echo $startime,',',$endtime;
        $sql = "select count(*) as num from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where ";//limit $offset,$limit
        $count      = $model->query($sql);// 查询满足要求的总记录数 $map表示查询条件
        $Page       = new Page($count[0]['num']);// 实例化分页类 传入总记录数
        $show       = $Page->show();// 分页显示输出
        $offset     = $Page->firstRow;
        $limit      = $Page->listRows;

        $sql = "select a.sncode,a.kd_id,b.saleprice,b.title,b.sort,b.categray from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where limit $offset,$limit";//
        $list = $model->query($sql);

        if($type==1){
            //联通结算
            $sql = "select sum(b.saleprice) as total from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where ";
            $totalprice =  $model->query($sql);
        }else{
            //物流结算
            $expArr = getExpress(false,'ALL');
            $kdprice = 0;
            foreach($expArr as $v){
                //$exp[$v['id']] = $v['price'];
                $num = M('Prize')->where(array('kd_id'=>$v['id'],'wl_bal'=>1))->count();
                $kdprice = $num*$v['price'] + $kdprice;
            }
            $totalprice[0]['total'] = (float)$kdprice;
        }

        $this->assign('list',$list);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('totalprice',$totalprice[0]['total']);
        $this->assign('query',array('starttime'=>$startime,'endtime'=>$endtime,'exp'=>$kdtype,'type'=>$type));

        //分类，商品级别
        $this->assign('sortarr',D('Goods')->getSortarr());
        $this->assign('categray',D('Goods')->getCategray());
        //物流公司
        $this->assign('express',getExpress(true));
        //是否是管理员
        $this->assign('isAdmin',$this->userinfo['roleid']==1?true:false);
        $this->display('balance');
    }

    public function export(){
        $parameters = I('parameters','','urldecode');
        $parameters = json_decode(stripslashes($parameters),true);

        if(isset($parameters['status']) && $parameters['status']>-1){
            $map[] = "a.status='".$parameters['status']."'";
        }
        
        if(isset($parameters['exp']) && $parameters['exp']){
            $map[] = "a.kd_id=".$parameters['exp'];//取出所属快递公司
        }
        if(isset($parameters['sort']) && !empty($parameters['sort'])){
            $map[] = "b.sort='".$parameters['sort']."'";
        }
        if(isset($parameters['cate']) && !empty($parameters['cate'])){
            $map[] = "b.categray='".$parameters['cate']."'";
        }
        $model = new Model();
        $where = implode(' and ',$map);

        $order = "id desc";
        $limit = 1000;
        $sql = "select a.*,b.sort,b.categray from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where order by $order limit $limit";
        $data = $model->query($sql);
        $sortarr = D('Goods')->getSortarr();
        $categray = D('Goods')->getCategray();
        //查询所有物流商户
        $express = getExpress(true);
        //--------------------------------导出开始--------------------------------
        Vendor('PHPExcel.PHPExcel');
        // Vendor('PHPExcel.PHPExcel.IOFactory');
        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $filename = $status ? "已配送管理.xls" : "未配送管理.xls";
        //商品总数
        $dataNum = count($data);
        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '姓名')
            ->setCellValue('B1', '联系电话')
            ->setCellValue('C1', '收货地址')
            ->setCellValue('D1', '商品码')
            ->setCellValue('E1', '商品级别')
            ->setCellValue('F1', '分类')
            ->setCellValue('G1', '备注')
            ->setCellValue('H1', '提交时间')
            ->setCellValue('I1', '状态')
            ->setCellValue('J1', '单号');

        for ($i=0; $i < $dataNum; $i++) {
            $row = $data[$i];
            $str = "";
            if($row['status']==1){
                $str = "已配送";
                if($row['kd_id']>0){
                    $str .= "(已分配给：".$express[$row['kd_id']].")";
                }
            }else{
                $str = "待配送";
                if($row['kd_id']>0){
                    $str .= "(已分配给：".$express[$row['kd_id']].")";
                }
            }
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . ($i+2), $row['username'])
                ->setCellValue('B' . ($i+2), $row['phone'])
                ->setCellValue('C' . ($i+2), str_replace(' ','',$row['area']) . $row['address'] )
                ->setCellValue('D' . ($i+2), $row['sncode'])
                ->setCellValue('E' . ($i+2), $sortarr[$row['sort']])
                ->setCellValue('F' . ($i+2), $categray[$row['categray']])
                ->setCellValue('G' . ($i+2), $row['remark'])
                ->setCellValue('H' . ($i+2), date('Y-m-d H:i:s',$row['create_time']))
                ->setCellValue('I' . ($i+2), $str)
                ->setCellValue('J' . ($i+2), $row['kdcode']);
        }

        // Rename worksheet
        // $objPHPExcel->getActiveSheet()->setTitle('sheet0');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(60);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(25);
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=".$filename);
        header("Content-Transfer-Encoding:binary");

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit();
    }
    /**
     * 联通已结算，物流已结算 导出
     * @return [type] [description]
     */
    public function export1()
    {
        $parameters = I('parameters','','urldecode');
        $parameters = json_decode(stripslashes($parameters),true);


        $status = 1;
        $where = "a.status='$status' ";
        if($parameters['kdtype']){
            $where .= "and a.kd_id='".$parameters['kdtype']."' ";
        }
        if($parameters['type']=='1'){
            $where .= "and a.lt_bal=1 ";//联通已结算
        }elseif($parameters['type']=='2'){
            $where .= "and a.wl_bal=1 ";//物流已结算
        }
        if($parameters['starttime'] && $parameters['endtime']){
            $where .= "and (a.create_time>".strtotime($parameters['starttime'])." and a.create_time<".strtotime($parameters['endtime']).") ";
        }

        $model = new Model();
        $order = "id desc";
        $limit = 1000;
        $sql = "select a.sncode,a.kd_id,b.saleprice,b.title,b.sort,b.categray from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where limit $limit";//
        $data = $model->query($sql);
        // var_dump($data);exit();
        if($parameters['type']==1){
            //联通结算
            $sql = "select sum(b.saleprice) as total from ve_prize a left join ve_goods b on a.sncode = b.sncode where $where ";
            $totalprice =  $model->query($sql);
        }else{
            //物流结算
            $expArr = getExpress(false,'ALL');
            $kdprice = 0;
            foreach($expArr as $v){
                $num = M('Prize')->where(array('kd_id'=>$v['id'],'wl_bal'=>1))->count();
                $kdprice = $num*$v['price'] + $kdprice;
            }
            $totalprice[0]['total'] = (float)$kdprice;
        }

        $sortarr = D('Goods')->getSortarr();
        $categray = D('Goods')->getCategray();
        //查询所有物流商户
        $express = getExpress(true);
        //--------------------------------导出开始--------------------------------
        Vendor('PHPExcel.PHPExcel');
        // Vendor('PHPExcel.PHPExcel.IOFactory');
        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $filename = $parameters['type']==1 ? "联通已结算订单.xls" : "物流已结算订单.xls";
        //总数
        $dataNum = count($data);
        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '商品码')
            ->setCellValue('B1', '商品名称')
            ->setCellValue('C1', '商品级别')
            ->setCellValue('D1', '分类')
            ->setCellValue('E1', '联通商城价')
            ->setCellValue('F1', '物流');

        for ($i=0; $i < $dataNum; $i++) {
            $row = $data[$i];
            
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . ($i+2), $row['sncode'])
                ->setCellValue('B' . ($i+2), $row['title'])
                ->setCellValue('C' . ($i+2), $sortarr[$row['sort']] )
                ->setCellValue('D' . ($i+2), $categray[$row['categray']])
                ->setCellValue('E' . ($i+2), $row['saleprice'])
                ->setCellValue('F' . ($i+2), $express[$row['kd_id']]);
                
        }
        $objPHPExcel->getActiveSheet()->mergeCells('A'.($dataNum+2).':F'.($dataNum+2)); 
        // Rename worksheet
        // $objPHPExcel->getActiveSheet()->setTitle('sheet0');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . ($dataNum+2), '总金额：'.$totalprice[0]['total']);

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=".$filename);
        header("Content-Transfer-Encoding:binary");

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit();
    }
}